package lomasky.xui;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/12 0012.
 */

public class ImgSelectDialog extends Dialog {


    private static final String TAG = "zjt";

    DisplayMetrics dm;
    PhotoAdapter adapter;
    private RecyclerView recyclerView;
    private android.widget.TextView cancelbt;
    private android.widget.TextView okbt;

    private Context context;

    public void setMaxCount(int max_count) {
        this.max_count = max_count;
    }

    private int max_count = 9;
    private int select_count = 0;


    public void setSelectedLisenter(SelectedLisenter selectedLisenter) {
        this.selectedLisenter = selectedLisenter;
    }

    public SelectedLisenter selectedLisenter;

    public ImgSelectDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    public ImgSelectDialog(@NonNull Activity context) {
        super(context, R.style.imgselect_dialog);
        this.context = context;
        //获得屏幕宽度高度
        dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
        Rect frame = new Rect();
        context.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);



        p.height = dm.heightPixels  ;
        p.width = dm.widthPixels;
        p.gravity = Gravity.BOTTOM;
        getWindow().setAttributes(p);
        LayoutInflater mLayoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        View rootview = mLayoutInflater.inflate(R.layout.layout_img_grid, null);

        okbt = (TextView) rootview.findViewById(R.id.ok_bt);
        cancelbt = (TextView) rootview.findViewById(R.id.cancel_bt);
        okbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectedLisenter.onSelected(getSelectedList());
                dismiss();
            }
        });
        cancelbt.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dismiss();
                    }
                }
        );


        recyclerView = (RecyclerView) rootview.findViewById(R.id.recyclerView);


        final GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
        recyclerView.setLayoutManager(gridLayoutManager);

        recyclerView.addItemDecoration( new DividerGridItemDecoration(  context));
        recyclerView.setHasFixedSize(true);
        setContentView(rootview);
        adapter = new PhotoAdapter();
        recyclerView.setAdapter(adapter);

    }


    public void init() {
        //cp获取全部图片
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver mContentResolver = getContext().getContentResolver();

        // 只查询jpeg和png的图
        Cursor cur = mContentResolver.query(mImageUri, null,
                MediaStore.Images.Media.MIME_TYPE + "=?",
                new String[]{"image/jpeg"},
                MediaStore.Images.Media.DATE_MODIFIED);
        List<ImgItem> paths = new ArrayList<>();
        adapter.clear();
        for (String s : selectedList) {
            adapter.add(new ImgItem(s, true));
        }

        if (cur.moveToLast()) {
            String image_path;
            do {
                image_path = cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA));
                if (!selectedList.contains(image_path)) {
                    paths.add(new ImgItem(image_path, false));
                }

            } while (cur.moveToPrevious());
        }


        adapter.addAll(paths);


    }

    public List<String> getSelectedList() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < adapter.data.size(); i++) {
            if (adapter.data.get(i).isSelected()) {
                list.add(adapter.data.get(i).getPath());
            }
        }
        return list;
    }

    public void setSelectedList(List<String> selectedList) {
        this.selectedList = selectedList;
        select_count = this.selectedList.size();
        init();

    }

    List<String> selectedList = new ArrayList<>();

    public interface SelectedLisenter {
        public void onSelected(List<String> list);


    }

    public class ImgItem {
        public String path;
        public boolean isSelected;

        public ImgItem(String path, boolean isSelected) {
            this.path = path;
            this.isSelected = isSelected;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public boolean isSelected() {
            return isSelected;
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }

    @Override
    public void show() {
        super.show();

    }

    public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {


        public List<ImgItem> getData() {
            return data;
        }

        List<ImgItem> data = new ArrayList<>();

        @Override
        public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.photo_img_item, parent, false);
            PhotoViewHolder vh = new PhotoViewHolder(view);
            return vh;
        }

        public void add(ImgItem t) {
            insert(t, data.size());
        }

        public void clear() {
            int size = data.size();
            data.clear();
            notifyItemRangeRemoved(0, size);
        }

        public void addAll(List<ImgItem> items) {
            if (items.isEmpty()) {
                return;
            }
            int startIndex = data.size();
            data.addAll(startIndex, items);
            notifyItemRangeInserted(startIndex, data.size());
        }

        @Override
        public void onBindViewHolder(final PhotoViewHolder holder, final int position) {
            final ImgItem imgItem = adapter.data.get(position);


            holder.checkBox.setChecked(imgItem.isSelected());
            holder.itemView.setClickable(true);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (imgItem.isSelected()) {
                        imgItem.setSelected(false);
                        select_count--;
                        adapter.notifyItemChanged(position);
                    } else {
                        if (select_count >= max_count) {
                            Toast.makeText(context, "最多只能选择" + max_count + "张图片", Toast.LENGTH_SHORT).show();
                        } else {
                            imgItem.setSelected(true);
                            select_count++;
                            adapter.notifyItemChanged(position);
                        }

                    }


                }
            });


            Glide.with(getContext())
                    .load(data.get(position).getPath())
                    .override(dm.widthPixels / 3, dm.widthPixels / 3)
                    .placeholder(R.drawable.pictures_no)
                    .into(holder.imageView);


        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        public void insert(ImgItem t, int position) {
            data.add(position, t);
            notifyItemInserted(position);
        }

        class PhotoViewHolder extends RecyclerView.ViewHolder {

            public ImageView imageView;
            public CheckBox checkBox;

            public PhotoViewHolder(View itemView) {
                super(itemView);
                checkBox = (CheckBox) itemView.findViewById(R.id.checkbox);
                imageView = (ImageView) itemView.findViewById(R.id.img);
                imageView.setLayoutParams(new FrameLayout.LayoutParams(dm.widthPixels / 3, dm.widthPixels / 3));

            }
        }
    }
}
